package com.sz.mes.excel.listener;

import com.diboot.core.util.BeanUtils;
import com.diboot.core.util.ContextHelper;
import com.diboot.core.util.V;
import com.sz.mes.excel.model.GoodsImportModel;
import com.diboot.file.excel.listener.FixedHeadExcelListener;
import com.sz.mes.entity.Goods;
import com.sz.mes.service.GoodsService;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
* 商品 导入Listener定义
* @author hem
* @version 1.0
* @date 2023-12-22
* Copyright © szhs
*/
public class GoodsImportListener extends FixedHeadExcelListener<GoodsImportModel> {
    private static final String GOODS_CODE = BeanUtils.convertToFieldName(GoodsImportModel::getGoodsCode);
    /**
    * 自定义校验规则
    * @param dataModelList    待保存的数据
    * @param requestParams  请求参数
    */
    @Override
    protected void additionalValidate(List<GoodsImportModel> dataModelList, Map<String, Object> requestParams) {
        // 附加校验
        // 对 用户编号、用户名 是否重复进行校验
        List<String> goodsCodeList = new ArrayList<>();
        for (GoodsImportModel excelModel : dataModelList) {
            if (goodsCodeList.contains(excelModel.getGoodsCode())) {
                excelModel.addComment(GOODS_CODE, "编号重复");
            }
            goodsCodeList.add(excelModel.getGoodsCode());

        }
        // 对用户编号在系统中是否重复进行校验
        List<String> duplicateGoodsCodeList = ContextHelper.getBean(GoodsService.class).filterDuplicateGoodsCode(goodsCodeList);
        for (String duplicateGoodsCode : duplicateGoodsCodeList) {
            dataModelList.get(goodsCodeList.indexOf(duplicateGoodsCode)).addComment(GOODS_CODE, "该编号在系统中已存在");
        }
    }

    /**
    * 保存数据
    * @param dataModelList 待保存的数据
    * @param requestParams 请求参数
    */
    @Override
    protected void saveData(List<GoodsImportModel> dataModelList, Map<String, Object> requestParams) {
        if (V.isEmpty(dataModelList)) {
            return;
        }
        List<Goods> entityList = BeanUtils.convertList(dataModelList, Goods.class);
        ContextHelper.getBean(GoodsService.class).createEntities(entityList);
    }
}